import React, { Component } from "react";
import { createForm } from "rc-form";
import { withRouter } from "react-router-dom";
import { getLogin, getCart } from "../../data/api";
import axios from "axios";
import {
  List,
  InputItem,
  WhiteSpace,
  NavBar,
  Icon,
  Button,
  Toast,
  Flex,
} from "antd-mobile";
class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // 用户名
      username: "",
      // 密码
      password: "",
    };
  }
  componentDidMount() {
    if (
      !this.props.loginState &&
      this.props.location.state &&
      this.props.location.state.from.pathname !== "/login"
    ) {
      //如过跳转页面时不是登录状态，先跳转登录页面
      Toast.info("请先登录", 1);
    }
  }
  //点击登录
  handleLogin = (props) => {
    this.props.form.validateFields((error, value) => {
      if (error) {
        //错误，校验不通过
        Toast.fail("请检查数据是否输入正确", 1);
      } else {
        let obj = {
          //提交前去掉空格
          username: value.username.replace(/\s/g, ""),
          password: value.password,
        };
        getLogin(obj).then((res) => {
          // console.log(res);
          const {
            meta: { status, msg },
            message,
          } = res;
          //状态码为200即登录成功
          if (status === 200) {
            //登录成功将token设置在请求头里
            let { token } = message;
            axios.defaults.headers.common["fffff"] = token;
            // console.log(token);
            window.sessionStorage.setItem("token",token);
            // 修改userReducer中的登录状态
            // this.props.changeLoginState({Login: true, token})
            // 登录成功同步购物车数据
            getCart().then((res) => {
              // console.log(res.token);
              //将获取到的数据解构
              const {
                meta: { status },
                message,
              } = res;
              //判断状态码为200获取购物车数据成功
              if (status === 200) {
                //判断购物车是否为空
                if (message.cart_info) {
                  //不为空同步购物车，修改cartReducer中的购物车数量
                  this.props.snycCart(
                    Object.values(JSON.parse(message.cart_info))
                  );
                }
              }
            });
            //获取location中的from
            const { from } = this.props.location.state || {from: { pathname: "/" }, };
            //获取pathname
            let pathname = from.pathname;
            console.log(pathname)
            // if (pathname === "/login") {
            //   pathname = "/my";
            // }
            //登录成功弹出提示框 ，1秒后消失
            Toast.success(msg, 1, () => {
              this.props.history.push(pathname);
            });
          } else {
            //否则提示错误信息
            Toast.fail(msg, 1);
          }
        });
      }
    });
  };
  render() {
    const { getFieldError, getFieldProps } = this.props.form;

    return (
      <div className="myLogin">
        {this.props.location.pathname === "/login" ? (
          <NavBar
            mode="dark"
            leftContent={<Icon type="left" />}
            onLeftClick={() => this.props.history.push("/home")}
          >
            登录
          </NavBar>
        ) : (
          ""
        )}
        <List renderHeader={() => "请登录"}>
          <InputItem
            type="phone"
            placeholder="请输入手机号"
            clear
            {...getFieldProps("username", {
              //输入框失焦时验证
              validateTrigger: "onBlur",
              //验证规则
              rules: [
                { required: true, message: "用户名不能为空" },
                { min: 11, message: "手机号码必须为11位" },
              ],
            })}
            //验证不通过时设置error为true
            error={getFieldError("username") ? true : false}
            //输入框输入改变时同时同步数据大state中的username
            onChange={(v) => {
              this.setState({
                username: v,
              });
            }}
            //将state中的username赋值给输入框
            value={this.state.username}
          >
            用户名
          </InputItem>
          <InputItem
            type="password"
            placeholder="请输入密码"
            clear
            {...getFieldProps("password", {
              validateTrigger: "onBlur",
              rules: [
                {
                  required: true,
                  message: "密码不能为空",
                },
                { min: 6, message: "密码不能低于六位数" },
              ],
            })}
            error={getFieldError("password") ? true : false}
            onChange={(v) => {
              this.setState({
                password: v,
              });
            }}
            value={this.state.password}
          >
            密码
          </InputItem>
          <WhiteSpace />
          <Flex justify="center">
            <Button
              type="primary"
              size="small"
              className="bottom-button"
              style={{ marginRight: 10 }}
              onClick={this.handleLogin}
            >
              立即登录
            </Button>
            <Button
              type="warning"
              size="small"
              className="bottom-button"
              onClick={() => this.props.history.push("/register")}
            >
              免费注册
            </Button>
          </Flex>
          <WhiteSpace />
        </List>
      </div>
    );
  }
}

export default createForm()(withRouter(Login));
